
const express = require("express")
// 创建路由对象
const router = express.Router()
// 引入数据库连接池
const pool = require("../../db/db.js")
// 引入封装后的响应结果
const Response = require("../../utils/ResponseData.js")
// 引入表单校验模块joi
const joi = require("joi")

/**
 * 用户相关接口
 * 包括删除用户、查询用户
 * RestFull风格
 * 请求方式不同:
 *          查询:get
 *          增加:post
 *          修改:put
 *          删除:delete
 * 请求路径携带参数不同:通过动态参数方式传参
*      举例:
*          后端:/petDiary/get/:id
*          前端:/petDiary/get/1
 *  */
// 删除日志
/**
 * 
 */
router.delete("/petUser/delete/:id", (req, res) => {
    let { id } = req.params
    let schema = joi.object({ id: joi.number().required() })
    let { error } = schema.validate(req.params)
    if (error) {
        res.send(Response.error(error))
        console.log(error);
        return
    }
    const sql = "delete from user where u_id = ?"
    pool.query(sql, [id], (err, result) => {
        console.log(result);
        if (err) {
            res.send(Response.error("删除失败!", 500))
        }
        if (result && result.affectedRows > 0) {
            res.send(Response.success(null, "删除成功!"))
        } else {
            res.send(Response.error("删除失败!", 500))
        }



    })
})


// 查询用户
/**
 * 请求url:http://localhost:3000/petUser/get/:page/:pageSize/:keywords
 * 参数:
 * 
 */
router.get("/petUser/get/:page/:pageSize/:keywords", async (req, res) => {
    console.log("params", req.params);
    let { page, pageSize, keywords } = req.params
    let schema = joi.object({
        page: joi.number().required(),
        pageSize: joi.number().max(10).required(),
        keywords: joi.string().required()
    })

    let { error, value } = schema.validate(req.params)
    if (error) {
        res.send(Response.error(error))
        return
    }
    try {
        const startIndex = (page - 1) * pageSize
        pageSize = parseInt(pageSize)
        if (keywords == "''") keywords = ''
        // 查询每页信息
        const sql1 = "select * from (select * from user where u_name like ? or u_email like ? )d1 limit ?,?"
        const result1 = await pool.querySync(sql1, [`%${keywords}%`, `%${keywords}%`, startIndex, pageSize])
        // 查询总条数
        const sql2 = "select count(u_id) as count from(select * from user where u_name like ? or u_email like ? )d1"
        const result2 = await pool.querySync(sql2, [`%${keywords}%`, `%${keywords}%`])
        console.log(result2);
        // 总条数
        const total = result2[0].count
        // 总页数=总条数%pageSize==0?总条数/pageSize:总条数/pageSize+1
        // 总页数=Math.ceil(总条数/pageSize)
        const maxPage = Math.ceil(total / pageSize)

        res.send(Response.success({
            page,
            pageSize,
            total,
            maxPage,
            result1,
        }))
    } catch (e) {
        res.send(Response.error(e))
    }
})
module.exports = router